package cn.eaay.stock.service.impl;

import cn.eaay.stock.common.enums.ResponseCode;
import cn.eaay.stock.mapper.SysUserMapper;
import cn.eaay.stock.pojo.SysUser;
import cn.eaay.stock.service.UserService;
import cn.eaay.stock.vo.req.LoginReqVo;
import cn.eaay.stock.vo.resp.LoginRespVo;
import cn.eaay.stock.vo.resp.R;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        // 校验登录请求参数
        if (vo == null || Strings.isNullOrEmpty(vo.getUsername())
                || Strings.isNullOrEmpty(vo.getPassword()) || Strings.isNullOrEmpty(vo.getRkey())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }

        // 校验验证码不能为空
        if (Strings.isNullOrEmpty(vo.getCode())) {
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_NOT_EMPTY.getMessage());
        }

        // 从redis中根据rKey获取对应验证码
        String rCode = redisTemplate.opsForValue().get(vo.getRkey());

        // 校验验证码是否过期
        if (Strings.isNullOrEmpty(rCode)) {
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_EXPIRED.getMessage());
        }

        // 校验验证码
        if (!Objects.equals(vo.getCode(), rCode)) {
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_ERROR.getMessage());
        }
        // 清除redis的key
        redisTemplate.delete(vo.getRkey());

        // 根据用户名获取用户信息
        SysUser user = sysUserMapper.findByUserName(vo.getUsername());
        // 若查询的用户为null，或用户密码不匹配，则返回错误信息
        if (null == user || !passwordEncoder.matches(vo.getPassword(), user.getPassword())) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        user.setPassword(null);

        // 校验通过，拷贝属性给登录响应对象
        LoginRespVo respVo = new LoginRespVo();
        BeanUtils.copyProperties(user, respVo);
        return R.ok(respVo);
    }
}
